<template>
  <li v-if="!isClosed" :class="{active:isActive}">
    <a href="javascript:void(0)" @click="click" class="tab">
      <i v-if="icon !== undefined" :class="icon"></i>
      {{label}}&nbsp;
      <a v-if="closable" class="icon-close" @click.stop.prevent="close">
        <i class="fa fa-times"></i>
      </a>
    </a>
  </li>
</template>

<script>
  import {mapState} from "vuex"
  import {HOME} from "../../assets/js/global"
  import {SET_ACTIVE_TAB, REMOVE_CACHED_TAB} from "../../store/mutationTypes"

  export default {
    name: "Tab",
    data() {
      return {
        isClosed: false
      }
    },
    computed:mapState({
      isActive(state) {
        return state.Tab.activeTab === this.label;
      }
    }),
    props: {
      label: {
        type: String,
        required:true
      },
      url: {
        type: String,
        required: true
      },
      icon: String,
      closable: Boolean
    },
    methods: {
      click() {
        this.$router.replace(this.url);
        this.$store.commit(SET_ACTIVE_TAB, this.label);
      },
      close() {
        this.isClosed = true;
        let index = this.$store.state.Tab.cachedTabs.findIndex(item=>item.label===this.label);
        this.$store.commit(REMOVE_CACHED_TAB, index);
        if (this.$store.state.Tab.cachedTabs.length === 0
          || (this.$store.state.Tab.activeTab === this.label && index === 0)) {
          this.$store.commit(SET_ACTIVE_TAB, HOME);
          this.$router.replace("/")
        } else if(this.$store.state.Tab.activeTab === this.label) {
          this.$store.commit(SET_ACTIVE_TAB, this.$store.state.Tab.cachedTabs[index - 1].label);
          this.$router.replace(this.$store.state.Tab.cachedTabs[index - 1].url);
        }
      }
    }
  }
</script>

<style scoped>
  .icon-close {
    display: none;
    margin-left: 5px;
  }
  .tab:hover>.icon-close {
    display: block;
    position: absolute;
    right: 5px;
    top: 10px
  }
</style>



// WEBPACK FOOTER //
// Tab.vue?1177df53
